<?php
namespace app\common\controller;
use think\Controller;
use think\Db;
class Weixin extends Controller{

//    private $AppId="wxd1ee2d95f4728599";
//    private $AppSecret="379afea64ce138af311d42cca3c4bdd2";
    private $AppId="wx155a07475f8ffb49";
    private $AppSecret="51d30dea7dfb6589513446d6ef8af2fa";

    #获取微信code
    public function GetWeixinCode(){

        $cur_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $scope='snsapi_base';
        $oauthUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->AppId.'&redirect_uri='.urlencode($cur_url).'&response_type=code&scope='.$scope.'&state=oauth#wechat_redirect';
        header('Location:'.$oauthUrl);
    }
    #获取微信code
    public function GetSnsapiCode(){

        $cur_url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $scope='snsapi_userinfo';
        $oauthUrl='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->AppId.'&redirect_uri='.urlencode($cur_url).'&response_type=code&scope='.$scope.'&state=oauth#wechat_redirect';
        header('Location:'.$oauthUrl);
    }
    #获取openid和uniond
    public function GetAuthorization(){

        $jsonrt=$this->getJson('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->AppId.'&secret='.$this->AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code');
        return $jsonrt;
    }
    #根据全局access_token和openid查询用户信息
    public function GetWeixinInfo($openid){

        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/user?access_token=".$this->GetAccessToken()."&openid=".$openid."&lang=zh_CN";
        $userinfo = $this->getJson($get_user_info_url);
        return $userinfo;
    }
    #获取微信AccessToken
    public function GetAccessToken(){

        $url="https://tool.gkzzd.cn/index/index/getAccessToken";
//        dump(header('Location:'.$url));exit;
//        return  header('Location:'.$url);  //Location和":"之间无空格。
        $rs= json_decode($this->curlGet($url),true);
//       dump($rs);exit;
        return $rs['data'];
    }
    //文本安全内容检测接口
    public function MsgSecCheck($content){
        $url="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=".$this->GetAccessToken();
        $rs= json_decode(curl2($url,['content'=>$content]),true);
        return $rs;
    }
    //抓取微信JSON数据
    public function getJson($url){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }


    //老师回答问题发送模板消息
    public function answerSendMessage($question_id,$db,$type)
    {
        switch ($type){
            case 1: //院校直通车
                $url="/pages/me/me/me_quiz?name=school";
                break;
            case 2:  //春季高考
                $url="/pages/vocationalEdu/voc_my_consult_enroll?name=school";
                break;
            case 3:  //机构
                $url="/pages/me/me/me_quiz?name=jg";
                break;
        }
        $rs=Db::name($db)
            ->alias('a')
            ->field('a.question,a.answer,FROM_UNIXTIME(a.time_a,\'%Y-%m-%d %H:%i:%s\') time_a,b.openid,a.nick_name_a')
            ->join('app_zd_user b','a.user_id_q=b.user_id','left')
            ->where(['a.id'=>$question_id])
            ->find();
        if(empty($rs))return false;
        if(empty($rs['openid']))return false;
        if(mb_strlen($rs['question'])>20){
            $rs['question']=mb_substr($rs['question'],0,17).'...';
        }
        if(mb_strlen($rs['answer'])>20){
            $rs['answer']=mb_substr($rs['answer'],0,17).'...';
        }
//        $rs['user_name']=mb_substr($rs['user_name'],0,1);
//        $rs['school']=$rs['school'].$rs['user_name'].'老师';
        if(mb_strlen($rs['nick_name_a'])>10){
            $rs['nick_name_a']=mb_substr($rs['nick_name_a'],0,7).'...';
        }

        $ACCESS_TOKEN = $this->GetAccessToken();
        $template_id = '6XOlk-GSKobG15Rbk-iuAVX1wKLoPYceYS3qGJSXoVs';//配置的模板id
        $send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $ACCESS_TOKEN;
        $template = array(
            'touser' => $rs['openid'],
            'template_id' => $template_id,
            'page' => $url,
            'data' => array(
                'thing1' => array('value' => $rs['answer']),
                'time2' => array('value' => $rs['time_a']),
                'name3' => array('value' => $rs['nick_name_a']),
                'thing4' => array('value' => $rs['question']),
                'thing5' => array('value' => '高考早知道祝您考上理想大学！'),)
        );
        $this->post_wx($send_template_url, $template);
    }


    public function get_accessing_data(){ //获取昨日接口访问数据
        
        $url="https://api.weixin.qq.com/datacube/getweanalysisappidvisitpage?access_token=".$this->GetAccessToken()."";
        $date=date('Ymd',time()-86400);
//        $time['begin_date']=$date;
//        $time['end_date']=$date;
        $arr=['begin_date'=>$date,
                'end_date'=>$date
            ];
        $res=$this->post_wx($url,$arr);
        return json_decode($res,true);
    }

    public function post_wx($send_template_url, $template)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $send_template_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($template));
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    public  function curl2($url, $data)
    {
        //dump(json_encode($data, JSON_UNESCAPED_UNICODE));
        if ($url && count($data)) {
            $headers = ['Content-Type' => 'application/json'];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        }
    }

    public static function curlGet($url = '', $options = array())
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}